package cn.server.impl;

import java.io.File;
import java.net.InetAddress;

import org.apache.catalina.connector.Connector;
import org.apache.catalina.startup.Tomcat;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.coyote.http11.AbstractHttp11JsseProtocol;

import cn.server.conf.WebServerParam;

public class WebServer extends BaseServer {
	/**
	 * Logger for this class
	 */
	private static final Log logger = LogFactory.getLog(WebServer.class);

	@Override
	public void startServer() {
		long startTime = System.currentTimeMillis();
		int port = param.getPort();
		try {
			WebServerParam wp = (WebServerParam) param;
			Tomcat tomcat = new Tomcat();
			tomcat.setBaseDir(System.getProperty("user.dir"));
			tomcat.setPort(port);
			Connector connector = tomcat.getConnector();
			AbstractHttp11JsseProtocol<?> protocol = (AbstractHttp11JsseProtocol<?>) connector.getProtocolHandler();
			protocol.setSessionTimeout(wp.getSessionTimeout()); // 分钟
			protocol.setMaxThreads(wp.getMaxThread());
			protocol.setConnectionTimeout(wp.getConnectionTimeout());
			// modify by wq for 绑定ip设置
			if (StringUtils.isNotBlank(param.getIp()))
				protocol.setAddress(InetAddress.getByName(param.getIp()));
			// TODO 增加一些tomcat的扩展配置,暂不实现
			tomcat.addWebapp("/", new File(wp.getWebappPath()).getCanonicalPath());
			tomcat.enableNaming();// 执行这句才能支持JDNI查找
			connector.setURIEncoding(wp.getEncoding());
			connector.setUseBodyEncodingForURI(true);
			tomcat.setSilent(true);
			tomcat.start();
			System.out.println("Tomcat started in " + (System.currentTimeMillis() - startTime) + " ms.");
			tomcat.getServer().await();// 让服务器一直跑
		} catch (Throwable e) {
			logger.error("error start server!", e);
			throw new RuntimeException("error start server!", e);
		} finally {
		}
	}
}
